from requests import get
import config
import pymysql
from time import sleep

play = config.play()  # 初始化
api_text = play[1]  # api文本内容(dict类型)
translate = play[4]  # 调用有道翻译
create_table = play[5]  # 创建数据表文件


def file_config():  # 获取数据库连接的基本信息
    file = open('./config.txt', mode='r', encoding='utf-8')
    file_database = open('database.txt', 'r')
    try:
        content = eval(file.read())
        database = eval(file_database.read())
        content['database'] = database['database']
        file.close()
        file_database.close()
        return content
    except Exception as err:
        file.close()
        file_database.close()
        return "数据库配置文件错误，请检查config.txt文件"


# mysql 拥有创建数据库的权限
host = file_config()['host']
user = file_config()['user']
password = file_config()['password']
port = int(file_config()['port'])
db = file_config()['database']
mysel_english_name = {}  # 将名字翻译成英文并且加入到字典
for name in api_text:
    english_names = translate(name)
    mysel_english_name[name] = english_names


def insert_into():  # 获取数据，并插入到数据库当中
    for api_name in api_text:
        api_url = api_text[api_name]
        for url in api_url:
            response = get(url=url).text
            try:
                if response[0] == '{' and response[-1] == '}':
                    for name_subset in eval(response):
                        response = eval(response)[name_subset]
            except:
                pass
            english_name = mysel_english_name[api_name]
            try:
                con = pymysql.connect(host=host, user=user, passwd=password, port=port,db=db)
                cur = con.cursor()
                cur.execute(f"insert into {english_name} value('{response}');")
                con.commit()
                cur.close()
                con.close()
                print(api_name, response)
            except Exception as err:
                print('insert错误信息: ', err)


def distinct():  # 检查数据库重复数据，并且去重
    try:
        con = pymysql.connect(host=host, user=user, passwd=password, port=port,db=db)
        cur = con.cursor()
        for chinese in mysel_english_name:
            english = mysel_english_name[chinese]
            CREATE = f'CREATE TABLE {english}s as SELECT DISTINCT * FROM {english};'
            DROP = f'DROP TABLE IF EXISTS {english};'
            RENAME = f'ALTER TABLE {english}s RENAME {english};'
            cur.execute(CREATE)
            cur.execute(DROP)
            cur.execute(RENAME)
            con.commit()
        cur.close()
        con.close()
    except Exception as err:
        print('distinct错误信息: ', err)


# 开始运行
def start():
    while True:
        insert_into()
        sleep(int(file_config()['sleep_time']))
